package model

import (
	"github.com/jinzhu/gorm"
)

type ArticleComment struct {
	*Model
	Content string `json:"content"`

	UserId    int `json:"user_id"`
	ArticleId int `json:"article_id"`
	ReplyId   int `json:"reply_id"`
}

type CommentPart struct {
	ID        int    `json:"id"`
	UserId    int    `json:"user_id"`
	Content   string `json:"content"`
	CreatedOn int    `json:"created_on"`

	NickName  string `json:"nick_name"`
	AvatarUrl string `json:"avatar_url"`
}

func (ac ArticleComment) TableName() string {
	return "article_comment"
}

func (ac ArticleComment) Create(db *gorm.DB) error {
	return db.Create(&ac).Error
}

func (ac ArticleComment) All(db *gorm.DB, pageOffset, pageSize int) ([]*CommentPart, error) {
	var comments []*CommentPart

	if pageSize > 0 && pageOffset >= 0 {
		db = db.Offset(pageOffset).Limit(pageSize)
	}

	err := db.Table(ac.TableName()).
		Where("article_id = ? AND article_comment.is_del = ? AND reply_id = ?", ac.ArticleId, 0, 0).
		Select("article_comment.id, article_comment.user_id, article_comment.content, " +
			"article_comment.created_on, user.nick_name, user.avatar_url").
		Joins("join user on article_comment.user_id = user.id").
		Scan(&comments).Error

	return comments, err
}

func (ac ArticleComment) GetReply(db *gorm.DB) ([]*CommentPart, error) {
	var comments []*CommentPart

	err := db.Table(ac.TableName()).
		Where("is_del = ? AND reply_id = ?", 0, ac.ID).
		Select("id, user_id, content, created_on").Scan(&comments).Error

	return comments, err
}
